import json
from lab.common.base_model_view_set import BaseModelViewSet
from lab.common.pagination import CustomPageNumberPagination
from lab.common.response import OK, NotFound
from lab.device.models import STATUS_ACTIVE, Appointment, Device, Lab
from lab.device.serializers import AppointmentSerializer, AppointmentWriteSerializer, DeviceListSerializer, DeviceMaintenanceSerializer, LabListSerializer, MyAppointmentSerializer
from lab.device.views import APPOINTMENT_STATUS_DICT
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi


class SuperUserViewSet(BaseModelViewSet):
    """
    list:
        获取管理员端实验室列表(0-待审批，1-通过，2-拒绝，3-取消)
    """
    serializer_class = LabListSerializer

    def get_queryset(self):
         return Lab.objects.filter(status=STATUS_ACTIVE)
    
    def list(self, request, *args, **kwargs):
        appointments = Appointment.objects.filter(status=APPOINTMENT_STATUS_DICT.get('pending')).order_by('-created_time')[:5]
        labs = self.get_queryset()
        response = {
            'pending_approval': {'appointment_count': len(appointments), 'credit_count': 24},
            'labs': LabListSerializer(labs, many=True).data
        }
        return OK(data=response)
    
class SuperUserAppointmentViewSet(BaseModelViewSet):
    """
    list:
        获取管理员端预约列表
    """
    queryset = Appointment.objects.all()
    serializer_class = AppointmentSerializer
    write_serializer_calss = AppointmentWriteSerializer
    pagination_class = CustomPageNumberPagination
    lookup_field='id'
    
    @swagger_auto_schema(
        manual_parameters=[
            openapi.Parameter(
                'status', 
                openapi.IN_QUERY, 
                description="预约状态-pending,pass,reject,cancel", 
                type=openapi.TYPE_STRING
            )
        ]
    )
    def list(self, request, *args, **kwargs):
        status = APPOINTMENT_STATUS_DICT.get(request.GET.get('status'))
        appointments = Appointment.objects.all()
        if status:
            appointments = appointments.filter(status=status)
        queryset = self.paginate_queryset(appointments.all())
        return self.get_paginated_response(MyAppointmentSerializer(queryset, many=True).data)
    
class SuperUserAppointmentOperationViewSet(BaseModelViewSet):
    """
    update:
        同意或拒绝预约
    """
    queryset = Appointment.objects.all()
    lookup_field='id'

    @swagger_auto_schema(
        manual_parameters=[
            openapi.Parameter(
                'status', 
                openapi.IN_QUERY, 
                description="预约状态-pass,reject", 
                type=openapi.TYPE_STRING
            )
        ]
    )
    def update(self, request, id, *args, **kwargs):
        appointment = Appointment.objects.filter(id=id).first()
        if appointment:
            status = request.GET.get('status')
            appointment.status = APPOINTMENT_STATUS_DICT.get(status)
            if status == 'reject':
                appointment.reason = json.loads(request.body).get('reason')
            appointment.save()
            response = AppointmentSerializer(self.get_object()).data
            return OK(data=response)
        else:
            return NotFound()
        
class SuperUserDeviceViewSet(BaseModelViewSet):

    """
    update:
        设置维护时间
    """
    serializer_class = DeviceListSerializer
    write_serializer_calss = DeviceMaintenanceSerializer
    queryset = Device.objects.all()
    lookup_field = 'id'

    def update(self, request, id, *args, **kwargs):
        obj = self.get_object()
        obj.status = request.data.get('status')
        if obj.status == 0:
            obj.maintain_date = request.data.get('maintain_date')
            obj.maintain_type = request.data.get('maintain_type')
        obj.save()
        return OK(DeviceListSerializer(obj).data)
